package com.tiance.integration.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tiance.exception.BusinessException;
import com.tiance.integration.ProxyBeansFactory;
import com.tiance.integration.config.CommonProperties;
import com.tiance.utils.HttpUtil;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by 雷霆 on 2019/1/30.
 *
 * Description：微信
 *
 * Modification History:
 *
 * @version 1.0.0
 *
 */
public class WechatClient {

	private   static     Logger log        = LoggerFactory.getLogger(WechatClient.class);

	protected static CommonProperties commonProperties = ProxyBeansFactory.getInstance().getBean(CommonProperties.class);

	private static String LOG_PREFIX ="WechatClient|微信参数===>";
	/**
	 * 获取openid
	 */
	public static String getOpenid(String appid,String secret,String code) throws IOException {

		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		String param = "appid=" + appid + "&secret=" + secret + "&code=" + code
					   + "&grant_type=authorization_code";
		url = url + "?" + param;
		// 发送http请求
		HttpClient getHttpClient = new HttpClient();
		getHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 8000);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		String result ;
		String openid = "";

			log.info(LOG_PREFIX+"开始获取openid.url="+url);
			int statusCode = getHttpClient.executeMethod(getMethod);
			log.info(LOG_PREFIX+"结束获取openid.返回code:" + statusCode);
			if (statusCode != 200) {
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取openid.失败：响应码=" + statusCode);
				throw new BusinessException("微信公众号.请求微信.获取openid.失败：响应码=" + statusCode);
			}
			result = getMethod.getResponseBodyAsString().trim();
			log.info(LOG_PREFIX+"微信公众号获取OPENID,响应结果:{}",result);

			if (result == null || "".equals(result)) {
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取openid.失败.响应结果不应为空");
				throw new BusinessException("微信公众号.请求微信.获取openid.失败：响应码为：200，响应结果为空=" );
			}

			Map json = (Map) JSONObject.parse(result);

			openid = (String) json.get("openid");
			if (openid == null || "".equals(openid)) {
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取openid.失败,失败原因:{}",result);
				throw new BusinessException("微信公众号.请求微信.获取openid.失败：响应码为：200，未获取到OPENID" );
			}

		return openid;
	}



	/**
	 * 获取Accesstoken
	 * @return
	 */
	public static AccessToken getAccessToken() throws IOException {
		String param = "?grant_type=client_credential&appid="+commonProperties.getWechatAppId()+"&secret="+commonProperties.getWechatSecret();
		String url = 	WechatConst.getAccessToken +param;
		HttpClient getHttpClient = new HttpClient();
		getHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 8000);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		AccessToken accessToken =null;
		String result;

			log.info(LOG_PREFIX+"开始请求微信.获取授权token：url="+url);
			int statusCode = getHttpClient.executeMethod(getMethod);
			log.info(LOG_PREFIX+"结束请求微信.获取授权token：返回结果code=" +statusCode);
			if (statusCode!=200){
				throw new BusinessException("微信公众号.请求微信.获取授权token.失败：响应码=" + statusCode );

			}
			result = getMethod.getResponseBodyAsString().trim();
		log.info(LOG_PREFIX+"微信公众号.请求微信.获取授权token. result"+result);

		if (result == null || "".equals(result)) {
				throw new BusinessException("微信公众号.请求微信.获取授权token.失败.响应结果不应为空");

			}
			accessToken = JSON.parseObject(result,AccessToken.class);
			if(null==accessToken){
				throw new BusinessException("微信公众号.请求微信.获取授权token.失败 ,获取结果为空：");
			}
//			if(!("0".equals(accessToken.getErrcode()))){
//				throw new BusinessException("微信公众号.请求微信.获取授权token.失败 ,原因："+accessToken.getErrmsg());
//			}

		return accessToken;
	}



	/**
	 * 获取Ticket
	 * @return
	 */
	public static JsapiTicket getTicket() throws IOException {
		JsapiTicket jsapiTicket =null;

		String param = "?type=jsapi&access_token="+TokenUtil.getAccessToken();
		String url = 	WechatConst.getTicket +param;
		HttpClient getHttpClient = new HttpClient();
		getHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 8000);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		String result;

			log.info(LOG_PREFIX+"开始请求微信.获取Ticket：url="+url);
			int statusCode = getHttpClient.executeMethod(getMethod);
			log.info(LOG_PREFIX+"结束请求微信.获取Ticket：返回结果code=" +statusCode);
			if (statusCode!=200){
				log.error(LOG_PREFIX+"微信公众号.请求微信.获取Ticket.失败：响应码=" + statusCode);
				return jsapiTicket;
			}
			result = getMethod.getResponseBodyAsString().trim();
		log.info(LOG_PREFIX+"微信公众号.请求微信.获取Ticket. result"+result);

		if (result == null || "".equals(result)) {
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取Ticket.失败.响应结果不应为空");
				return jsapiTicket;
			}
			jsapiTicket = JSON.parseObject(result,JsapiTicket.class);


		return jsapiTicket;
	}





	/**
	 * 发送模板消息
	 * @param access_token
	 * @param
	 * @param paymsgtemple  消息模板和业务相关故而放到上层 。 如果公告模板比较多再抽取
	 * @return
	 */
	public  static MsgTmpResult sendtemplatemsg(String access_token, PayMsgtemple paymsgtemple) {
		String param = "?"+"access_token="+access_token;
		String url = 	WechatConst.sendtemplatemsg +param;
		HttpClient getHttpClient = new HttpClient();
		getHttpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);

		PostMethod postMethod = new PostMethod(url);

		postMethod.setRequestEntity(new StringRequestEntity(com.alibaba.fastjson.JSON.toJSONString(paymsgtemple,true)));
		postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 8000);
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		MsgTmpResult msgTmpResult=null;
		String result = "";
		try {
			log.info(LOG_PREFIX+"开始请求微信.获取授权token：请求参数=");
			int statusCode = getHttpClient.executeMethod(postMethod);
			log.info(LOG_PREFIX+"结束请求微信.获取授权token：返回结果statusCode=" +statusCode);
			if (statusCode!=200){
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取授权token.失败：响应码=" + statusCode);
				return msgTmpResult;
			}
			result = postMethod.getResponseBodyAsString().trim();
			if (result == null || "".equals(result)) {
				log.info(LOG_PREFIX+"微信公众号.请求微信.获取授权token.失败.响应结果不应为空");
				return msgTmpResult;
			}
			msgTmpResult = JSON.parseObject(result,MsgTmpResult.class);

		} catch (Exception e) {
			log.error(LOG_PREFIX+"微信公众号.请求微信.获取授权token.失败",e);
		}
		return msgTmpResult;
	}
	public static WxUserInfo getUserInfo(String openId) throws IOException {

		String param = "access_token="+TokenUtil.getAccessToken()+"&openid=" +openId + "&lang=zh_CN";
		String url = WechatConst.userinfo + "?" + param;
		String result=HttpUtil.get(url);
		WxUserInfo userInfo = JSON.parseObject(result,WxUserInfo.class);
		return userInfo;
	}

	public static String getCode(String appId, String redirectURI){
		String url;
		String redirect_uri = redirectURI+commonProperties.getContextPath()+"/front/memberCenter/toIndex.action";
		String redirect_uriEncode = URLEncoder.encode(redirect_uri);
		String param = "appid=" + appId + "&redirect_uri=" + redirect_uriEncode
					   + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
		url = WechatConst.authorize + "?" + param;
		log.info(LOG_PREFIX+"微信地址"+url);
		return url;
	}

}
